package com.flexcloudsdk.web;
import java.io.IOException;


import java.util.logging.Logger;
import java.io.PrintWriter;

import com.flexcloudsdk.capabilities.CloudCapabilities;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CloudCapabilitiesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(CloudCapabilitiesServlet.class.getName());
	public CloudCapabilities capabilities = new CloudCapabilities();
	static final String getServicesCall = "getServices";
	private String sourceMethod;
	private String sourceClass;

	public CloudCapabilitiesServlet()
	{
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		sourceClass = CloudCapabilitiesServlet.class.getName();
		log.info("*****CloudCapabilitiesServlet constructor********");
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);
	}

	@Override
	protected void doPost(HttpServletRequest req,	HttpServletResponse resp)
			throws ServletException, IOException {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);

		resp.setContentType("text/plain");
		PrintWriter writer=resp.getWriter();
	    writer.println("<?xml version=\"1.0\"?>\n");
    		writer.println("<root>");
		
	   String operation = req.getParameter("operation");
		if (operation == null) {
			writer.println("<result>Must pass an operation</result>");
			 log.warning("operation passed is null for CloudCapabilities.");
			return;
		}
		if (operation.isEmpty()) {
			writer.println("<result>Must pass an operation</result>");
			 log.warning("operation passed is empty for CloudCapabilities.");
			return;
		}
		
		writer.println("</root>");
	}

	@SuppressWarnings("unused")
	private void handleNullOperation(PrintWriter writer, HttpServletRequest req) {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);

		log.warning("operation is null");
		writer.println("<result>No operation found while calling "
				+ req.getServerName() + "servlet</result>");
	}
	
	@SuppressWarnings("unused")
	private void handleEmptyOperation(PrintWriter writer, HttpServletRequest req) {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);

		log.warning("operation is empty");
		writer.println("<result>Must pass an operation in calling "
				+ req.getServerName() + "servlet</result>");
	}

}
